﻿

//==================================================================================
//  FaceBookClass
//==================================================================================
function FaceBookClass()
{
    this.version = '1.0';
    this.callingApi = 'http://api.facebook.com/restserver.php';
    this.loggedInUserId = null;
    this.apiKey = "c5204e5168effecd58962a1fb1e80cb2";
    this.secretKey = "429718a4b768ce5b237e1620afcff5cf";
}

//==================================================================================
//  getNotifications
//==================================================================================
FaceBookClass.prototype.getNotifications = function(sessionKey)
{
    var root = this.callMethod(this.apiKey, sessionKey, this.secretKey, 'facebook.notifications.get', []);
    
    //  Messages   
    var messages = root.getElementsByTagName("messages")[0];
    var oMessage = new NotsElement(
        FaceBookClass.getNodeValue(messages.childNodes, "unread"),
        FaceBookClass.getNodeValue(messages.childNodes, "most_recent"),
        "Message");
    //  Pokes   
    var pokes = root.getElementsByTagName("pokes")[0];
    var oPoke = new NotsElement(
        FaceBookClass.getNodeValue(pokes.childNodes, "unread"),
        FaceBookClass.getNodeValue(pokes.childNodes, "most_recent"),
        "Poke");
    //  Shares   
    var shares = root.getElementsByTagName("shares")[0];
    var oShare = new NotsElement(
        FaceBookClass.getNodeValue(shares.childNodes, "unread"),
        FaceBookClass.getNodeValue(shares.childNodes, "most_recent"),
        "Share");
    //  Friend Requests
    var oFriendRequests = new NotsElement(
        root.getElementsByTagName("friend_requests")[0].childNodes.length, 
        "", 
        "Friend_Request");
    //  Group Invites   
    var oGroupInvites = new NotsElement(
        root.getElementsByTagName("group_invites")[0].childNodes.length, 
        "", 
        "Group_Invite");
    //  Event Invites
    var oEventInvites = new NotsElement(
        root.getElementsByTagName("event_invites")[0].childNodes.length, 
        "", 
        "Event_Invite");
        
    return new NotificationsObject(oMessage, oPoke, oShare, oFriendRequests, oGroupInvites, oEventInvites);
}
 
//==================================================================================
//  Notification Element
//==================================================================================
function NotsElement(count, lastId, type)
{
    this.Count = count;
    this.LastID = lastId;
    this.Type = type;
}

//==================================================================================
//  NotificationsObject
//==================================================================================
function NotificationsObject(messages, pokes, shares, friendinvites, groupinvites, eventinvites)
{
    this.Messages = messages;
    this.Pokes = pokes;
    this.Shares = shares;
    this.FriendInvitations = friendinvites;
    this.GroupInvitations = groupinvites;
    this.EventInvitations = eventinvites;
}

//==================================================================================
//  getCurrentUser
//==================================================================================
FaceBookClass.prototype.getCurrentUser = function(sessionKey)
{
    // Get the current userid.
    if(!this.loggedInUserId)
    {
        var useridroot = this.callMethod(this.apiKey, sessionKey, this.secretKey, 'facebook.users.getLoggedInUser', null);
        this.loggedInUserId = useridroot.getElementsByTagName('users_getLoggedInUser_response')[0].text;
    }
    
    var uids = ([this.loggedInUserId]).join();
    var paramArray = ['fields=uid, first_name, last_name, name', 'uids=' + uids];
    var root = this.callMethod(this.apiKey, sessionKey, this.secretKey, 'facebook.users.getInfo', paramArray);
    var users = root.getElementsByTagName('user');

    if (users.length > 0)
    {
        var user = users[0].childNodes;
        var uid = FaceBookClass.getNodeValue(user, 'uid');
        var name = FaceBookClass.getNodeValue(user, 'name');
        var firstName = FaceBookClass.getNodeValue(user, 'first_name');
        var lastName = FaceBookClass.getNodeValue(user, 'last_name');
        return new User(uid, name, firstName, lastName);
    }
    else
        return null;
}

//==================================================================================
//  User
//==================================================================================
function User(uid, name, firstName, lastName)
{
    this.id = uid;
    this.firstName = firstName;
    this.lastName = lastName;
    this.name = name;
}

//==================================================================================
//  Generic method that generates an XML HTTP request to the Facebook API server.
//==================================================================================
FaceBookClass.prototype.callMethod = function(api_key, session_key, secret_key, method, parms)
{
    var paramArray = new Array();
    paramArray.push('method='+ method); 
    paramArray.push('call_id='+ this.GetCallId());
    paramArray.push('api_key='+ api_key);
    paramArray.push('session_key='+ session_key);
    paramArray.push('v='+ this.version);
    if(parms) paramArray = paramArray.concat(parms);
    paramArray.push('sig='+ this.GenerateSig(paramArray, secret_key));
    var headers = [ { Key: "Content-type", Value: "application/x-www-form-urlencoded" } ];
    var xmlDoc = FaceBookClass.getRequestXml(this.callingApi, null, headers, paramArray.join("&"));
    return xmlDoc;
}

//==================================================================================
//  Generates a new sessionKey
//==================================================================================
FaceBookClass.prototype.getSessionKey = function()
{
    var sessionKey = "";
    if (System.Gadget.Settings.read("Token") + "" != "")
    {
        var paramArray = new Array();
        paramArray.push('method=facebook.auth.getSession'); 
        paramArray.push('auth_token=' + System.Gadget.Settings.read("Token")); 
        paramArray.push('api_key='+ this.apiKey);
        paramArray.push('v='+ this.version);
        paramArray.push('sig='+ this.GenerateSig(paramArray, this.secretKey));
        
        var headers = [ { Key: "Content-type", Value: "application/x-www-form-urlencoded" } ];
        var xmlDoc = FaceBookClass.getRequestXml(this.callingApi, null, headers, paramArray.join("&"));
        if (xmlDoc && xmlDoc.selectNodes("//session_key").length > 0)
        {
            sessionKey = xmlDoc.selectNodes("//session_key")[0].text;
            this.loggedInUserId = xmlDoc.selectNodes("//uid")[0].text;
        }
    }
    return sessionKey;
}

//==================================================================================
//  Generates and validates a new AuthToken
//==================================================================================
FaceBookClass.prototype.getAuthToken = function()
{
    var authToken = '';
    var paramArray = new Array();
    
    paramArray.push('method=facebook.auth.createToken'); 
    paramArray.push('api_key='+ this.apiKey);
    paramArray.push('v='+ this.version);
    paramArray.push('sig='+ this.GenerateSig(paramArray, this.secretKey));
    
    var headers = [ { Key: "Content-type", Value: "application/x-www-form-urlencoded" } ];
    
    var xmlDoc = FaceBookClass.getRequestXml(this.callingApi, null, headers, paramArray.join("&"));
    if (xmlDoc && xmlDoc.selectNodes("//auth_createToken_response").length > 0)
    {
        authToken = xmlDoc.selectNodes("//auth_createToken_response")[0].text;
        window.showModalDialog("http://www.facebook.com/login.php?api_key=" + this.apiKey + "&v=1.0&popup&auth_token=" + authToken);
    }        
    return authToken;
}

//==================================================================================
//  Creates an MD5 signature for the facebook api
//==================================================================================
FaceBookClass.prototype.GenerateSig = function(paramArr, secret_key)
{   
    return hex_md5(paramArr.sort().join("") + secret_key);
}

//==================================================================================
//  Generates a random number to avoid replay attacks
//==================================================================================
FaceBookClass.prototype.GetCallId = function()
{
    return (new Date()).getTime() + '.00';
}

//==================================================================================
//  getNodeValue
//==================================================================================
FaceBookClass.getNodeValue = function(node, nodeName)
{
    for(var i = 0; i < node.length; i++)
    {
        if (node[i].nodeType != 1)
        {
        } 
        else if (node[i].firstChild != null)
        {
            if(node[i].nodeName == nodeName)
            {
                return node[i].firstChild.nodeValue;
            }
        }
    }
    return '';
}

//==================================================================================
//  getRequest
//==================================================================================
FaceBookClass.getRequest = function(url, key, headers, data)
{   
    var url = url;     
    if (key != null) url += "&key=" + key;
    
    var xmlhttp = new window.XMLHttpRequest();

    if(data && data.length > 0)
    {
        xmlhttp.open('POST', url, false); 
    }
    else
    {
        xmlhttp.open('GET', url, false);
    }

    if(headers && headers.length > 0)
    {
        for(var i = 0; i < headers.length; i++)
        {
            if(headers[i] && headers[i].Key && headers[i].Value) xmlhttp.setRequestHeader(headers[i].Key, headers[i].Value);
        }
    }
  	
    if(data && data.length > 0)
    {
        xmlhttp.send(data);
    }
    else
    {
        xmlhttp.send(null);
    }

    if(xmlhttp.readyState == 4 && xmlhttp.status == "200")
    {
        return xmlhttp;
    }
    else
    {
        throw "Unable to get data from '" + url + "': Error code " + xmlhttp.status;
    }
}

//==================================================================================
//  getRequestXml
//==================================================================================
FaceBookClass.getRequestXml = function(url, key, headers, data)
{
    return FaceBookClass.getRequest(url, key, headers, data).responseXML;
}
    
